import datetime

import numpy as np
import pandas as pd
from pandas import DataFrame

from .abstract_runner_framework import AbstractRunnerFrameWork, AbstractFrameWorkFactory, T
from .source_reader import PandasSourceReader
from algorithm.abstract_algorithm import AbstractAlgorithm
from common_config import *

columns = ['sn', 'start_time', 'end_time']

default_config = {
    "sagemaker_write_file": sagemaker_write_file
}


class SagemakerFactory(AbstractFrameWorkFactory):

    def create(self, params) -> AbstractRunnerFrameWork:
        file = default_config["sagemaker_write_file"] if 'sagemaker_write_file' not in params else params[
            'sagemaker_write_file']
        return SagemakerFrameWork(write_file=file)


class SagemakerFrameWork(AbstractRunnerFrameWork[DataFrame]):

    def close(self):
        pass

    def __init__(self, write_file):
        self.write_file = write_file

    def get_source(self, reader: PandasSourceReader) -> DataFrame:
        return reader.read()

    def filter(self, data: T) -> T:
        return data

    def detect(self, data: DataFrame, algorithm: AbstractAlgorithm) -> DataFrame:
        data = data.fillna(np.nan)
        data = data.replace({np.nan: None})
        result = pd.DataFrame(algorithm.run(data), columns=columns)
        result['protocol'] = algorithm.config.proto_col().value
        result['detect_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        result['p_date'] = result['end_time'].str[0:10]
        result['fault_code'] = algorithm.config.fault_code().value
        result['system_type'] = algorithm.config.system_tye().value
        result['version'] = algorithm.config.version()
        return result

    def write(self, data: DataFrame):
        data.to_csv(self.write_file)
        pass
